<template>
  <div class="product-detail-container page-container">
    <!-- 手机端样式容器 -->
    <div class="mobile-container">
      <!-- 顶部导航 -->
      <div class="mobile-header">
        <div class="header-left">
          <el-button link @click="goBack" class="back-btn">
            <svg viewBox="0 0 24 24" fill="currentColor" width="20" height="20">
              <path
                d="M20 11H7.83l5.59-5.59L12 4l-8 8 8 8 1.41-1.41L7.83 13H20v-2z"
              />
            </svg>
          </el-button>
        </div>
        <div class="header-title">商品详情</div>
        <div class="header-right"></div>
      </div>

      <!-- 商品图片轮播 -->
      <div
        class="product-images"
        v-if="
          productDetail.spuImagesList && productDetail.spuImagesList.length > 0
        "
      >
        <el-carousel :interval="4000" height="256px" class="image-carousel">
          <el-carousel-item
            v-for="(image, index) in productDetail.spuImagesList"
            :key="index"
          >
            <img
              :src="image"
              :alt="`商品图片${index + 1}`"
              class="carousel-image"
              @click="previewImage(image)"
              @error="handleImageError"
            />
          </el-carousel-item>
        </el-carousel>
      </div>

      <!-- 如果没有图片，显示占位符 -->
      <div
        class="product-images"
        v-else
        style="padding: 16px; text-align: center; color: #999"
      >
        <p>暂无商品图片</p>
      </div>

      <!-- 商品基本信息 -->
      <div class="product-info">
        <div class="product-title">{{ productDetail.spuName }}</div>
        <div class="product-subtitle">{{ productDetail.subTitle }}</div>

        <!-- 价格信息 -->
        <div class="price-section">
          <div class="current-price">
            <span class="price-label">价格：</span>
            <span class="price-value">¥{{ getMinPrice() }}</span>
            <span class="price-range" v-if="hasPriceRange()">
              - ¥{{ getMaxPrice() }}
            </span>
          </div>
          <div class="market-price" v-if="getMinMarketPrice() > 0">
            <span class="market-price-label">市场价：</span>
            <span class="market-price-value">¥{{ getMinMarketPrice() }}</span>
          </div>
        </div>

        <!-- 分类和标签 -->
        <div class="product-tags">
          <el-tag v-if="productDetail.categoryName" size="small" type="primary">
            {{ productDetail.categoryName }}
          </el-tag>
          <el-tag v-if="productDetail.labelName" size="small" type="success">
            {{ productDetail.labelName }}
          </el-tag>
        </div>
      </div>

      <!-- SKU选择 -->
      <div class="sku-section" v-if="skuList.length > 0">
        <div class="section-title">规格选择</div>
        <div class="sku-list">
          <div
            v-for="sku in skuList"
            :key="sku.id"
            class="sku-item"
            :class="{ selected: selectedSku?.id === sku.id }"
            @click="selectSku(sku)"
          >
            <div class="sku-specs">
              <el-tag
                v-for="(value, key) in parseSpecs(sku.specs)"
                :key="key"
                size="small"
                class="spec-tag"
              >
                {{ key }}: {{ value }}
              </el-tag>
            </div>
            <div class="sku-price">¥{{ sku.price }}</div>
            <div
              class="sku-stock"
              :class="{ 'low-stock': sku.stock <= sku.warnStock }"
            >
              {{
                sku.stock <= sku.warnStock ? "库存紧张" : "库存: " + sku.stock
              }}
            </div>
            <div class="sku-sales">已售：{{ sku.beautifySales }}+</div>
          </div>
        </div>
      </div>

      <!-- 商品详情 -->
      <div class="product-description">
        <div class="section-title">商品详情</div>
        <div
          class="description-content"
          v-html="productDetail.description"
        ></div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from "vue";
import { ElMessage } from "element-plus";
import { useRoute, useRouter } from "vue-router";
import { getWithAuth, postWithAuth } from "@/utils/request";

// 类型定义
interface ProductDetail {
  id?: string;
  spuCode: string;
  spuName: string;
  subTitle: string;
  categoryId: string | number;
  categoryName?: string;
  labelId?: string | number;
  labelName?: string;
  spuImagesList: string[];
  description: string;
  status: number;
  skuCount?: number;
  modifiedTime?: string;
}

interface ProductSku {
  id?: string;
  skuCode: string;
  spuId: string | number;
  specs: string | Record<string, any>;
  price: number;
  marketPrice: number;
  costPrice: number;
  stock: number;
  warnStock: number;
  image: string;
  status: number;
  cumulativeSales: number;
  beautifySales: number;
}

// 响应式数据
const route = useRoute();
const router = useRouter();

const productDetail = ref<ProductDetail>({} as ProductDetail);
const skuList = ref<ProductSku[]>([]);
const selectedSku = ref<ProductSku | null>(null);

// 获取商品详情
const fetchProductDetail = async () => {
  const productId = route.params.productId as string;
  if (!productId) {
    ElMessage.error("商品ID不存在");
    return;
  }

  try {
    const response = await postWithAuth(`/internal/product/detail`, {
      id: productId,
    });

    if (response.code === 0) {
      productDetail.value = response.data;
      console.log("商品详情数据:", productDetail.value);
      console.log("主图列表:", productDetail.value.spuImagesList);
      await fetchSkuList(productId);
    } else {
      ElMessage.error(response.message || "获取商品详情失败");
    }
  } catch (error) {
    console.error("获取商品详情失败:", error);
    ElMessage.error("获取商品详情失败");
  } finally {
  }
};

// 获取SKU列表
const fetchSkuList = async (productId: string) => {
  try {
    const response = await getWithAuth(
      `/internal/product/skuList?spuId=${productId}`
    );

    if (response.code === 0) {
      skuList.value = response.data;
      // 默认选择第一个SKU
      if (skuList.value.length > 0) {
        selectedSku.value = skuList.value[0];
      }
    } else {
      ElMessage.error(response.message || "获取SKU列表失败");
    }
  } catch (error) {
    console.error("获取SKU列表失败:", error);
    ElMessage.error("获取SKU列表失败");
  }
};

// 选择SKU
const selectSku = (sku: ProductSku) => {
  selectedSku.value = sku;
};

// 解析规格属性
const parseSpecs = (specs: string | Record<string, any>) => {
  if (typeof specs === "string") {
    try {
      return JSON.parse(specs);
    } catch {
      return {};
    }
  }
  return (specs as Record<string, any>) || {};
};

// 获取最低价格
const getMinPrice = () => {
  if (skuList.value.length === 0) return 0;
  return Math.min(...skuList.value.map((sku) => sku.price));
};

// 获取最高价格
const getMaxPrice = () => {
  if (skuList.value.length === 0) return 0;
  return Math.max(...skuList.value.map((sku) => sku.price));
};

// 获取最低市场价
const getMinMarketPrice = () => {
  if (skuList.value.length === 0) return 0;
  return Math.min(...skuList.value.map((sku) => sku.marketPrice));
};

// 是否有价格区间
const hasPriceRange = () => {
  return getMinPrice() !== getMaxPrice();
};

// 返回上一页
const goBack = () => {
  router.back();
};

// 图片预览
const previewImage = (imageUrl: string) => {
  window.open(imageUrl, "_blank");
};

// 图片加载错误处理
const handleImageError = (event: Event) => {
  console.error("图片加载失败:", event);
  const img = event.target as HTMLImageElement;
  img.src =
    "";
};

// 页面加载时获取数据
onMounted(() => {
  fetchProductDetail();
});
</script>

<style scoped>
.product-detail-container {
  min-height: 100vh;
  background-color: #f5f7fa;
}

.mobile-container {
  max-width: 414px;
  margin: 0 auto;
  background-color: white;
  min-height: 100vh;
  box-shadow: 0 0 20px rgba(0, 0, 0, 0.1);
}

/* 顶部导航 */
.mobile-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 12px 16px;
  background-color: white;
  border-bottom: 1px solid #ebeef5;
  position: sticky;
  top: 0;
  z-index: 100;
}

.header-left {
  flex: 1;
}

.back-btn {
  color: #606266;
  padding: 0;
}

.header-title {
  flex: 2;
  text-align: center;
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

.header-right {
  flex: 1;
}

/* 商品图片轮播 */
.product-images {
  margin-bottom: 16px;
  padding: 0 16px;
}

.image-carousel {
  border-radius: 8px;
  overflow: hidden;
}

.carousel-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
  cursor: pointer;
  border-radius: 8px;
}

/* 轮播图样式 */
:deep(.el-carousel__item) {
  overflow: hidden;
}

:deep(.el-carousel__item img) {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

/* 商品基本信息 */
.product-info {
  padding: 16px;
  border-bottom: 1px solid #ebeef5;
}

.product-title {
  font-size: 18px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 8px;
  line-height: 1.4;
}

.product-subtitle {
  font-size: 14px;
  color: #909399;
  margin-bottom: 12px;
  line-height: 1.4;
}

.price-section {
  margin-bottom: 12px;
}

.current-price {
  display: flex;
  align-items: center;
  margin-bottom: 4px;
}

.price-label {
  font-size: 14px;
  color: #606266;
  margin-right: 4px;
}

.price-value {
  font-size: 20px;
  font-weight: 600;
  color: #f56c6c;
}

.price-range {
  font-size: 16px;
  font-weight: 600;
  color: #f56c6c;
  margin-left: 4px;
}

.market-price {
  display: flex;
  align-items: center;
}

.market-price-label {
  font-size: 12px;
  color: #909399;
  margin-right: 4px;
}

.market-price-value {
  font-size: 12px;
  color: #909399;
  text-decoration: line-through;
}

.product-tags {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
}

/* SKU选择 */
.sku-section {
  padding: 16px;
  border-bottom: 1px solid #ebeef5;
}

.section-title {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 12px;
}

.sku-list {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.sku-item {
  padding: 12px;
  border: 1px solid #dcdfe6;
  border-radius: 6px;
  cursor: pointer;
  transition: all 0.2s ease;
}

.sku-item:hover {
  border-color: #409eff;
}

.sku-item.selected {
  border-color: #409eff;
  background-color: #f0f9ff;
}

.sku-specs {
  display: flex;
  flex-wrap: wrap;
  gap: 4px;
  margin-bottom: 8px;
}

.spec-tag {
  font-size: 12px;
}

.sku-price {
  font-size: 16px;
  font-weight: 600;
  color: #f56c6c;
  margin-bottom: 4px;
}

.sku-stock {
  font-size: 12px;
  color: #606266;
}

.sku-stock.low-stock {
  color: #f56c6c;
}

.sku-item {
  position: relative;
}

.sku-sales {
  position: absolute;
  right: 12px;
  bottom: 12px;
  font-size: 12px;
  color: #909399;
}

/* 商品详情 */
.product-description {
  padding: 16px;
  border-bottom: 1px solid #ebeef5;
}

.description-content {
  font-size: 14px;
  line-height: 1.6;
  color: #606266;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .sku-sales {
    right: 10px;
    bottom: 10px;
    font-size: 11px;
  }
}

@media (max-width: 480px) {
  .sku-sales {
    right: 8px;
    bottom: 8px;
    font-size: 10px;
  }
}

@media (max-width: 414px) {
  .mobile-container {
    max-width: 100%;
    box-shadow: none;
  }

  .sku-sales {
    right: 6px;
    bottom: 6px;
    font-size: 9px;
  }
}
</style>
